package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 付常莹
 * @description: TODO
 * @date 2022/12/4 11:30
 * 该实现类用于删除购物车，全选或全不选商品接口
 */
@Service
public class ICartServiceImlY implements ICartService {
    @Resource
    RedissonClient redissonClient;


    @Override
    public List<CartProductDto> getCartListById(Long userId) {
        return null;
    }

    @Override
    public void addToCart(CartRequest request) {

    }

    @Override
    public void updateCartNum(CartRequest request) {

    }

    /**
     * 购物车中的商品全选或全不选
     * @param request
     */
    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {
        RMap<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        Set<Long> longs = map.keySet();
        for (Long aLong : longs) {
            CartProductDto cartProductDto = map.get(aLong);
            cartProductDto.setChecked(request.getChecked());
            map.put(aLong, cartProductDto);
        }
    }

    /**
     * 删除购物车中的商品
     * @param uid
     * @param itemId
     */
    @Override
    public void deleteCartItem(Long uid, Long itemId) {
        RMap<Long, CartProductDto> map = redissonClient.getMap(uid.toString());
        map.remove(itemId);
//        CartProductDto cartProductDto = map.get(itemId);
//        map.remove(cartProductDto);
    }


    /**
     * 删除购物车中选中的商品
     * @param userId
     */
    @Override
    public void deleteCheckedItem(Long userId) {
        RMap<Long, CartProductDto> map = redissonClient.getMap(userId.toString());
        ArrayList<Long> keys = new ArrayList<>();
        Set<Long> longs = map.keySet();
        for (Long aLong : longs) {
            String checked = map.get(aLong).getChecked();
            if ("true".equals(checked)) {
                keys.add(aLong);
            }
        }
        for (Long key : keys) {
            map.remove(key);
        }
    }
}
